|
|
|
|
|
|
|
Public Function bFileExists(sFile As String) As Boolean
If Dir$(sFile) <> "" Then bFileExists = True Else bFileExists = False
End Function |
|
|
|
|
|
|
|
|
This function could then be used to check any filenames passed to the program by the user, as in the following example: |
|
|
|
|
|
|
|
|
Dim sUserFile As String
sUserFile = InputBox$("Enter the file name:")
If Not bFileExists(sUserFile) Then
MsgBox "The file does not exist. Please try again."
End
End If |
|
|
|
|
|
|
|
|
Notice that the code sample ends the program if the file does not exist, to prevent any errors that might occur later. Another way to handle this situation would be to keep asking the user for a filename until a valid filename is entered. |
|
|
|
|
|
|
|
|
Listing Files and Folders |
|
|
|
|
|
|
|
|
Another use of the Dir$ function is to return a list of files in the specified path. If you use the Dir command at an MS-DOS prompt, each matching file is listed on the screen. However, because the Dir$ function is designed to return only a single string variable, you have to use a loop and retrieve one filename at a time. (You also can display a list of files with a file list box, which is one of Visual Basic's default controls. These controls are covered extensively in Chapter 4, "Using Visual Basic's Default Controls.") |
|
|
|
|
|
|
|
|
Suppose that your C:\DATA directory contains several picture files with a BMP (bitmap) extension. The path used to retrieve these files with the Dir$ function would be C:\DATA\*.BMP. You can use the following lines of code to retrieve the filenames and add them to a list box: |
|
|
|
|
|
|
|
|
Dim sNextFile As String
sNextFile = Dir$("C:\Data\*.BMP")
While sNextFile <> ""
lstPictureList.AddItem sNextFile
sNextFile = Dir$
Wend |
|
|
|
|
|
|
|
|
In the preceding example, notice that only the file path to Dir$ is supplied on the first call. Each subsequent call to Dir$ has no arguments, indicating that you want to use the previous file path and move to the next filename in the list. When no more files match, Dir$ returns an empty string and the While loop terminates. |
|
|
|
|
CAUTION
|
|
|
|
|
When you use Dir$ in a loop, always exit the loop after an empty string is returned. If you try to make another call to Dir$ with no arguments, a runtime error occurs. |
|
|
|
|
|
|
|
|
|
|
The second, optional parameter of the Dir$ function is used to provide additional conditions (beyond the specified path) with which to select files. For example, using the constant |
|
|
|
|
|